package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private List<Map<String, Host>> serverList;

    public RequestProcessor(Socket socket, List<Map<String, Host>> serverList) {
        this.socket = socket;
        this.serverList = serverList;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            //遍历server,找到虚拟机
            for (Map<String, Host> hostMap : serverList) {
                for(Map.Entry<String, Host> a:hostMap.entrySet()){
                    if(request.getHost().equals(a.getKey())){
                        //根据url找到servlet，并执行
                        HttpServlet httpServlet = findServlet(a.getValue(),request.getUrl());
                        httpServlet.service(request,response);
                    }
                }
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private HttpServlet findServlet(Host host,String url){
        Object servlet=null;
        String[] url_patten = url.split("/");
        String contextStr = url_patten[1];
        String wrapperStr = "/"+url_patten[2];
        Map<String, Context> contextMap = host.getContextMap();
        for(Map.Entry<String, Context> a:contextMap.entrySet()){
            //根据host后第一个词组匹配context
            if(a.getKey().equals(contextStr)){
                Map<String, Wrapper> wrapperMap = a.getValue().getWrapperMap();
                for(Map.Entry<String, Wrapper> s:wrapperMap.entrySet()){
                    //根据实际的操作命令匹配wrapper——servlet
                    if(s.getKey().equals(wrapperStr)){
                        servlet = s.getValue().getServlet();
                    }
                }
            }
        }
        return (HttpServlet)servlet;
    }
}
